// pages/diagnose/diagnose.js
//引入始终工具
var utilClock = require('../../utils/utilClock');
Page({
  data: {
    appoint: {},
    diagnose: {
      appoint: {},
      patientSituation: '',
      diagnoseResult: '',
      medicineList: [],
      startDianoseTime: '',
      endDianoseTime: '',
      appointPay: 0,
      medicinePay: 0,
      allPay: 0,
      addInfo: '',
    },
    medicineInfo: [],
  },
  //一进来拿流水号和药品信息
  onLoad(options) {
    var that = this
    //一进来获取开始就诊时间
    var startDianoseTime = 'diagnose.startDianoseTime'
    that.setData({
      [startDianoseTime]: utilClock.formatTime(new Date())
    })
    console.log('开始就诊时间', that.data.diagnose.startDianoseTime)
    //获取流水号
    console.log(options.flowId)
    //根据流水号获取预约信息，包括预约信息、医师信息、用户信息、预约价钱
    wx.cloud.callFunction({
      name: 'appoint',
      data: {
        action: 'findFlowId',
        flowId:options.flowId,
      }
    }).then(res => {
      console.log('获取这个流水号的预约信息成功', res.result.data[0])
      var appointItem = 'diagnose.appoint'
      var appointPay = 'diagnose.appointPay'
      that.setData({
        appoint: res.result.data[0],
        [appointItem]: res.result.data[0],
        [appointPay]: res.result.data[0].doctorInfo.doctorPay,
      })
      //获取流水号信息后获取药品信息
      wx.cloud.callFunction({
        name: 'medicineInfo',
        data: {
          action: 'find',
        }
      }).then(res => {
        console.log('获取药品信息成功', res.result.data)
        that.setData({
          medicineInfo: res.result.data
        })
      }).catch(res => {
        console.log('获取药品信息失败', res)
      })

    }).catch(res => {
      console.log('获取这个流水号的预约信息失败', res)
    })
  },
  //获取患者情况
  getpatientSituation(e) {
    // console.log(e.detail.value)
    var patientSituation = 'diagnose.patientSituation'
    this.setData({
      [patientSituation]: e.detail.value
    })
  },
  //获取诊断结果
  getdiagnoseResult(e) {
    var diagnoseResult = 'diagnose.diagnoseResult'
    this.setData({
      [diagnoseResult]: e.detail.value
    })
  },

  //选择药品后返回药品id,并且生成药品列表medicineList
  change(e) {
    var that = this
    console.log('选的药的id', e.detail.id)
    var medicineId = e.detail.id
    //根据选择的药的id找到选择的药的信息
    for (var i = 0; i < that.data.medicineInfo.length; i++) {
      if (that.data.medicineInfo[i].medicineId == medicineId) {
        var medicineNameItem = that.data.medicineInfo[i].medicineName
        var medicineIdItem = that.data.medicineInfo[i].medicineId
        var medicineDossageItem = that.data.medicineInfo[i].medicineDossage
        var medicineUnitItem = that.data.medicineInfo[i].medicineUnit
        var medicineUnitBigItem = that.data.medicineInfo[i].medicineUnitBig
        var medicineSumItem = that.data.medicineInfo[i].medicineSum
        var medicinePriceItem = that.data.medicineInfo[i].medicinePrice
        var medicineWantItem = 1
        //根据选择的药的id找到选择的药的信息并合成对象
        var medicineInfoObj = {
          medicineName: medicineNameItem,
          medicineId: medicineIdItem,
          medicineDossage: medicineDossageItem,
          medicineUnit: medicineUnitItem,
          medicineUnitBig: medicineUnitBigItem,
          medicineWant: medicineWantItem,
          medicineSum: medicineSumItem,
          medicinePrice: medicinePriceItem,
        }
        //把选择的药的信息push到medicineList[]中去
        that.data.diagnose.medicineList.push(medicineInfoObj)
        //为了实时显示，用setdata
        var medicineList = 'diagnose.medicineList'
        that.setData({
          [medicineList]: that.data.diagnose.medicineList
        })
        console.log('选好的药物列表', that.data.diagnose.medicineList)
      }
    }
  },
  //修改药品需要的数量
  getmedicineWant(e) {
    var that = this
    for (var j = 0; j < that.data.diagnose.medicineList.length; j++) {
      //根据修改的药品id找到对应药品信息
      if (that.data.diagnose.medicineList[j].medicineId == e.currentTarget.dataset.medicineid) {
        //修改这个药品的需求数量
        var medicineWantItem = 'diagnose.medicineList[' + j + '].medicineWant'
        that.setData({
          [medicineWantItem]: parseInt(e.detail.value, 10)
        })
      }
    }
    console.log('修改药品需求数量的药物列表', that.data.diagnose.medicineList)
  },
  //取消选用这个药品
  delMedicine(e) {
    var that = this
    for (var k = 0; k < that.data.diagnose.medicineList.length; k++) {
      //根据修改的药品id找到对应药品信息
      if (that.data.diagnose.medicineList[k].medicineId == e.currentTarget.dataset.medicineid) {
        //删除这个药品的需求信息
        that.data.diagnose.medicineList.splice(k, 1)
        //实时删除显示
        var medicineListItem = 'diagnose.medicineList'
        that.setData({
          [medicineListItem]: that.data.diagnose.medicineList
        })
      }
    }
    console.log('删除药品需求的药物列表', that.data.diagnose.medicineList)
  },
  //提交
  commit() {
    var that = this
    wx.showLoading({
      title: '订单生成中......',
    })
    //提交时间和已经完成isOver标志
    var endDianoseTime = 'diagnose.endDianoseTime'
    var isOver = 'diagnose.appoint.isOver'
    that.setData({
      [endDianoseTime]: utilClock.formatTime(new Date()),
      [isOver]: true
    })
    //0、算出价钱（medicinePay、allPay）
    for (var x = 0; x < that.data.diagnose.medicineList.length; x++) {
      if (that.data.diagnose.medicineList[x].medicineSum < that.data.diagnose.medicineList[x].medicineWant) { //如果库存不足
        console.log('库存不足')
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              image: '/images/else/alarm.png',
              icon: 'none',
              title: '库存不足:' + that.data.diagnose.medicineList[x].medicineName,
            })
          },
        })
        return
      } else { //库存足够
        that.data.diagnose.medicinePay += that.data.diagnose.medicineList[x].medicinePrice * that.data.diagnose.medicineList[x].medicineWant
        console.log('每次循环累加后的药品总价', that.data.diagnose.medicinePay)
        //1、修改库存（medicineList）
        that.data.diagnose.medicineList[x].medicineSum -= that.data.diagnose.medicineList[x].medicineWant
      }
    }
    //总价
    that.data.diagnose.allPay = that.data.diagnose.medicinePay + that.data.diagnose.appointPay
    console.log('总价', that.data.diagnose.allPay)
    console.log('修改数量后的库存信息(medicineList)', that.data.diagnose.medicineList)

    //1、修改medicineInfo库存
    for (var y = 0; y < that.data.diagnose.medicineList.length; y++) {
      console.log('medicineList的id', that.data.diagnose.medicineList[y].medicineId)
      console.log('medicineList的sum', that.data.diagnose.medicineList[y].medicineSum)
      wx.cloud.callFunction({
        name: 'medicineInfo',
        data: {
          action: 'changeSum',
          medicineId: that.data.diagnose.medicineList[y].medicineId,
          medicineSum: that.data.diagnose.medicineList[y].medicineSum
        }
      }).then(res => {
        console.log('修改库存成功', res)
      }).catch(res => {
        console.log('修改库存失败', res)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '生成订单失败，请检查网络'
            })
          },
        })
      })
    }
    //2、修改appoint的isOver
    setTimeout(() => {
      wx.cloud.callFunction({
        name: 'appoint',
        data: {
          action: 'changeOverByFlowId',
          flowId: that.data.appoint.flowId,
          isOver: true,
        }
      }).then(res => {
        console.log('修改isOver状态成功', res)
        //3、上传所有到就诊信息数据库
        wx.cloud.callFunction({
          name: 'diagnose',
          data: {
            action: 'add',
            appoint: that.data.diagnose.appoint,
            patientSituation: that.data.diagnose.patientSituation,
            diagnoseResult: that.data.diagnose.diagnoseResult,
            medicineList: that.data.diagnose.medicineList,
            startDianoseTime: that.data.diagnose.startDianoseTime,
            endDianoseTime: that.data.diagnose.endDianoseTime,
            appointPay: that.data.diagnose.appointPay,
            medicinePay: that.data.diagnose.medicinePay,
            allPay: that.data.diagnose.allPay,
            addInfo: that.data.diagnose.addInfo,
            flowId:that.data.appoint.flowId
          }
        }).then(res=>{
          console.log('新建就诊信息成功',res)
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                title: '生成订单成功'
              })
            },
          })
          //4、跳转到订单列表,携带订单号
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/order/order?flowId='+that.data.appoint.flowId+'&isFromDiagnose='+true,
            })
          }, 300);
        }).catch(res=>{
          console.log('新建就诊信息失败',res)
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                icon: 'none',
                title: '生成订单失败，请检查网络'
              })
            },
          })
        })
      }).catch(res => {
        console.log('修改isOver状态失败', res)
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '生成订单失败，请检查网络'
            })
          },
        })
      })
    }, 1000);
  }
})